package com.williambucciero.mobilemuseum;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

import com.williambucciero.mobilemuseum.R;

public class BackgroundAlarmReceiver extends BroadcastReceiver  {
	DebugReporter reporter;
	@Override
	public void onReceive(Context ctxt, Intent i) {
		reporter = new DebugReporter(ctxt);
		ConnectivityManager conMgr =  (ConnectivityManager) ctxt.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
		
		if(updatedToday(ctxt)) {
			reporter.writeToFile("BAR: Already Updated Today.");
			return;
		}
		
		if(activeNetwork == null || !activeNetwork.isConnected() ){
			 reporter.writeToFile("BAR: Can't find nextwork.");
			 AlarmManager myAlarmMgr = (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
	    	 myAlarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, AlarmManager.INTERVAL_HOUR, PendingIntent.getBroadcast(ctxt, 0, new Intent(ctxt,BackgroundAlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT));
		}
		else {
			Calendar c = Calendar.getInstance();
			StartServiceOnBootReceiver.count = c.get(Calendar.DAY_OF_WEEK);

        	BitmapDownloaderTask task = new BitmapDownloaderTask();
        	task.setContext(ctxt);
        	try {
        		task.execute(new URL("http://www.williambucciero.com/" + findResolution(ctxt) + StartServiceOnBootReceiver.count + ".png"));
            } catch (Exception e) {
        		e.printStackTrace();
        	}
		}
        	
	}

	// Returns string of resolution text for the URL
	private String findResolution(Context ctxt){
		String toReturn;
		Display display = ((WindowManager)ctxt.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		DisplayMetrics outMetrics = new DisplayMetrics ();
		display.getMetrics(outMetrics);

		if(outMetrics.widthPixels == 480 ){
			toReturn = "800x480/";
			reporter.writeToFile("BAR: Screen size 800x480.");
		} else if(outMetrics.widthPixels == 720){
			toReturn = "1280x720/";
			reporter.writeToFile("BAR: Screen size 1280x720.");
		} else{
			toReturn = "480x320/";
			reporter.writeToFile("BAR: Screen size 480x320.");
		}
		return toReturn;
	}
	
	// Returns whether or not the photo was already updated today. This information is stored as a "String" in lastUpdated (as day of year)
	private boolean updatedToday(Context ctxt){
		try{
			DataInputStream in = new DataInputStream(ctxt.openFileInput("lastUpdated"));
			Calendar c = Calendar.getInstance();
			String tester = in.readUTF();
			if(c.get(Calendar.DAY_OF_YEAR)==Integer.parseInt(tester)){
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}
}

class BitmapDownloaderTask extends AsyncTask<URL, Void, Bitmap> {
	private Context ctxt;
	boolean downloadFailed = false;
	WakeLock myWakeLock = null;
	DebugReporter reporter;
	
	
	public void setContext(Context in){
		ctxt=in;
		reporter = new DebugReporter(ctxt);
		PowerManager pm = (PowerManager) ctxt.getSystemService(Context.POWER_SERVICE);
		myWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ctxt.getResources().getString(R.string.app_name));
		myWakeLock.acquire();
	}
    
    public Bitmap doInBackground(URL... url) {
    	Bitmap toReturn = null;
    	try {
    		BufferedInputStream in = new BufferedInputStream(url[0].openStream());
    		toReturn = BitmapFactory.decodeStream(in);
    		in.close();
			reporter.writeToFile("BAR(inner): Download Success.");
		} catch (Exception e) {
			reporter.writeToFile("BAR(inner): Download failed because of " + e.toString());
			toReturn=null;
		    e.printStackTrace();
		    downloadFailed = true;
		}
		return toReturn;
	}

    private Bitmap modifiedBitmap(Bitmap toModify, WallpaperManager screen){
    	Bitmap background = Bitmap.createBitmap(screen.getDesiredMinimumWidth(), screen.getDesiredMinimumHeight(), Config.ARGB_8888);
    	Canvas canvas = new Canvas(background);
        canvas.drawBitmap(background, new Matrix(), null);
        canvas.drawBitmap(toModify, background.getWidth()/2 - toModify.getWidth()/2, 0, null);
        return background;
    }
    @Override
    protected void onPostExecute(Bitmap bitmap) {
    	if(downloadFailed){
    		AlarmManager myAlarmMgr = (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
 	    	myAlarmMgr.set(0, AlarmManager.INTERVAL_HOUR, PendingIntent.getBroadcast(ctxt, 0, new Intent(ctxt,BackgroundAlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT));
    	}
    	else {
    		WallpaperManager myWallpaperManager = WallpaperManager.getInstance(ctxt);
    		try {
    			if(bitmap!=null){
    				myWallpaperManager.setBitmap(modifiedBitmap(bitmap,myWallpaperManager));
    				updateLastPhotoDate();
    			}
    		} catch (IOException e) {
	    		if(myWakeLock.isHeld()){
	    			myWakeLock.release();
	    		}
				e.printStackTrace();
			}
    	}
    	if(myWakeLock.isHeld()){
    		myWakeLock.release();
    	}
    }
    
    private void updateLastPhotoDate(){
		try{
			DataOutputStream out = new DataOutputStream(ctxt.openFileOutput("lastUpdated", Context.MODE_PRIVATE));
			Calendar c = Calendar.getInstance();
			out.writeUTF(((Integer)c.get(Calendar.DAY_OF_YEAR)).toString());
			out.close();
		} catch (Exception e) {
		}
    }
}

